//
//  XXMQTT.swift
//  XXIOT
//
//  Created by xx on 2024/8/19.
//

import Foundation
import CocoaMQTT
import FastSwiftSDK

// MARK: - 枚举
public typealias XXMQTTConnectCallBack = (String)->Void
public typealias XXMQTTMsgCallBack = (String,String)->Void


class XXMQTT:CocoaMQTT5Delegate{
    
    public static var shared = XXMQTT()
    var mqtt5:CocoaMQTT5?
    var topics:Array<String> = []
    var connectCallBack:XXMQTTConnectCallBack?
    var msgCallBack:XXMQTTMsgCallBack?
    var connectState = 0
    
    // 链接
    func content(host:String,port:UInt16 = 1833,username:String,password:String,topics:Array<String> = []){
        let clientID = "CocoaMQTT_" + String(ProcessInfo().processIdentifier)
        mqtt5 = CocoaMQTT5(clientID: clientID, host: host, port: 1883)
        mqtt5?.username = username //self.username
        mqtt5?.password = password //self.password
        mqtt5?.keepAlive = 60
        mqtt5?.delegate = self
        mqtt5?.connect(timeout: 10)
        if topics.count > 0 {
            self.topics = topics
        }
    }
    
    // 订阅
    func subseribes(topics:Array<String>){
        guard let mqtt = self.mqtt5 else {
            FastLog.debug("mqtt 未连接")
            return
        }
        var arr:Array<MqttSubscription> = []
        for topic in topics{
            let subscriptions = MqttSubscription(topic: topic)
            arr.append(subscriptions)
        }
        mqtt.subscribe(arr)
    }
    
    // 发送消息
    func send(topic:XXTOPIC,msg:String){
        guard let mqtt = self.mqtt5 else {
            FastLog.debug("mqtt 未连接")
            return
        }
        let roperties =  MqttPublishProperties()
        mqtt.publish(topic.rawValue, withString: msg, properties: roperties)
    }
    
    // MARK: delegate
    func mqtt5(_ mqtt5: CocoaMQTT5, didConnectAck ack: CocoaMQTTCONNACKReasonCode, connAckData: MqttDecodeConnAck?) {
        FastLog.debug("didConnectAck")
        connectCallBack?("didConnectAck")
        self.connectState = 1
        // 订阅
        self.subseribes(topics: self.topics)
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didPublishMessage message: CocoaMQTT5Message, id: UInt16) {
//        FastLog.debug("didPublishMessage")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didPublishAck id: UInt16, pubAckData: MqttDecodePubAck?) {
//        FastLog.debug("didPublishAck")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didPublishRec id: UInt16, pubRecData: MqttDecodePubRec?) {
//        FastLog.debug("didPublishRec")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveMessage message: CocoaMQTT5Message, id: UInt16, publishData: MqttDecodePublish?) {
        FastLog.debug("didReceiveMessage")
        let topic = message.topic
        let msg = message.string ?? ""
        msgCallBack?(topic,msg)
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didSubscribeTopics success: NSDictionary, failed: [String], subAckData: MqttDecodeSubAck?) {
//        FastLog.debug("didSubscribeTopics")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didUnsubscribeTopics topics: [String], unsubAckData: MqttDecodeUnsubAck?) {
        FastLog.debug("didUnsubscribeTopics")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveDisconnectReasonCode reasonCode: CocoaMQTTDISCONNECTReasonCode) {
        FastLog.debug("didReceiveDisconnectReasonCode")
    }
    
    func mqtt5(_ mqtt5: CocoaMQTT5, didReceiveAuthReasonCode reasonCode: CocoaMQTTAUTHReasonCode) {
        FastLog.debug("didReceiveAuthReasonCode")
    }
    
    func mqtt5DidPing(_ mqtt5: CocoaMQTT5) {
        FastLog.debug("mqtt5DidPing")
    }
    
    func mqtt5DidReceivePong(_ mqtt5: CocoaMQTT5) {
        FastLog.debug("mqtt5DidReceivePong")
    }
    
    func mqtt5DidDisconnect(_ mqtt5: CocoaMQTT5, withError err: Error?) {
        connectCallBack?("disconnect")
        self.connectState = 0
        if let err = err{
            FastLog.debug(err)
        }else{
            FastLog.debug("正常断开连接")
        }
        FastLog.debug("mqtt5DidDisconnect")
    }
    
}
 
